<?php


/**
 * Assumes team is in the season
 */
function usedTeam($team) {
    return $team->currentSeasonStats->played > 0;
}

/**
 * Assumes team is in the season
 */
function removableTeam($team) {
    return $team->currentSeasonStats->played == 0;
}

/**
 * Utility to get a readable form of the team name
 */
function getTeamName($team) {
    return $team->name . " (" . $team->coach->name . ") (" . $team->lastUpdate . ")";
}

function showSeasonTeams() {
    global $season, $teams, $races;
    // Addable is all teams that are not in the season. 
    $addableTeams = array ();
    $allTeams = loadAllTeams($races);
    foreach ($allTeams as $allTeam) {
        $matched = false;
        foreach ($teams->teams as $seasonTeam) {
            if ($allTeam->id == $seasonTeam->id) {
                $matched = true;
                continue;
            }
        }
        if (!$matched) {
            array_push($addableTeams, $allTeam);
        }
    }
    // Removeable teams are teams that are in the season and have not played a game yet
    $removeableTeams = array_filter($teams->teams, "removableTeam");
    // Teams that are in the season, but have played a game, so cannot be removed
    $usedTeams = array_filter($teams->teams, "usedTeam");
    uasort ($addableTeams, "coachSort");
    uasort ($removeableTeams, "coachSort");
    uasort ($usedTeams, "coachSort");
    echo<<< EOQ
      <form method="get" action="season_editor.php">
          <tr>
            <th>Add Teams</th>
            <th>Remove Teams</th>
            <th>Used Teams</th>
          </tr>
          <tr>
            <td>
              <select name="add_team_ids[]" multiple size="12">
EOQ;
    foreach ($addableTeams as $team) {
        $name = getTeamName($team);
        echo "<option value=\"$team->id\">$name</option>\n";
    }

    $coaches = loadCoaches();
    foreach ($coaches as $coach) {
        echo "<option value=\"$coach->name\">Create Team ($coach->name)</option>\n";
    }
    echo<<< EOQ
              </select>
            </td>
            <td>
              <select name="remove_team_ids[]" multiple size="12">

EOQ;
    foreach ($removeableTeams as $team) {
        $name = getTeamName($team);
        echo "<option value=\"$team->id\">$name</option>\n";
    }
    echo<<< EOQ
              </select>
            </td>
            <td><i>Teams already used in this season</i>
EOQ;
    foreach ($usedTeams as $team) {
        echo "<br />" . $team->getRosterLink() . "\n";
    }
    echo<<< EOQ
            </td>
          </tr>
          <tr>
            <td colspan="3" align="center"><input type="submit" name="updateSeason" value="Update Season"></td>
          </tr>
        </form>
EOQ;
}

function showConferences() {
    global $teams, $season;
    echo<<< EOQ
	<form method="post" action="season_editor.php">
EOQ;
    $i = 0;
    uasort ($teams->teams, "conferenceSort");
    foreach ($teams->teams as $team) {     
        $name = getTeamName($team);
        $row = getEchoTR($i++);
        echo<<< EOQ
	$row
		<td align="right">$name</td>
		<td colspan="2"><select name="conference$team->id">
EOQ;
        foreach ($season->conferences as $conference) {
            $selected = "";
            if (0 == strcmp($team->conference, $conference)) {
                $selected = " selected";
            }
            echo<<< EOQ
        		<option $selected>$conference</option>
EOQ;
        }
        echo<<< EOQ
			</select>
		</td>
	</tr>
EOQ;
    }
    echo<<< EOQ
	<tr>
		<td colspan="3" align="center"><input type="submit" name="updateConferences" value="Update Conferences"></td>
	</tr>
	</form>
EOQ;
}

/* Start of Page */
include_once ("includes/init.php");
if (!isCommissioner()) {
    $redirect = "index.php";
    $message = "Permission Denied, redirecting";
    include ("includes/redirect.php");
    return;
}
$newConference = getParam("newconference");
if (isset ($newConference)) {
	$newConferenceName = getParam("newConferenceName");
    $season->addConference($newConferenceName);
    $_SESSION["season"] = $season;
} else
	$updateSeason = getParam("updateSeason");
    if (isset ($updateSeason)) {
		$add_team_ids = $_POST["add_team_ids"];
        if (isset ($add_team_ids)) {
            foreach ($add_team_ids as $id) {
                if (!is_numeric($id)) {
                    $id = addNewTeam($id);
                }
                $rs = executeQuery("insert into seasons_teams (fk_season_id, fk_team_id) values ($season->id, $id)");
            }
        }
		$remove_team_ids = $_POST["remove_team_ids"];
        if (isset ($remove_team_ids)) {
            foreach ($remove_team_ids as $id) {
                $rs = executeQuery("delete from seasons_teams where fk_season_id=$season->id and fk_team_id=$id");
            }
        }
        $redirect = "season_editor.php?reload=true&season_id=$season->id";
        $redirectStr = "reloadling";
        $message = "Updated - reloading";
        include ("includes/redirect.php");
        return;
    } else
		$updateConferences = $_POST["updateConferences"];
        if (isset ($updateConferences)) {
        	foreach($teams->teams as $team) {
        		$newConference = getVariable("conference", $team->id, $_POST);
        		if (0 != strcmp($newConference, $team->conference)) {
        			$team->conference = $newConference;
        		    $season->updateConference($team);
        		}
        	}
	        $redirect = "season_editor.php?reload=true&season_id=$season->id";
	        $redirectStr = "reloadling";
	        $message = "Updated - reloading";
	        include ("includes/redirect.php");
	        return;
        }
include_once ("includes/header.php");

$image = $season->getImage();
echo<<< EOQ
<caption><h3>Season Teams Editor<br/>$season->season $image</h3></caption>
<form method="POST" action="season_editor.php">
  <tr>
    <th colspan="2"><input type="submit" name="newconference" value="Add Conference">
    <input type="text" size="32" maxsize="64" name="newConferenceName" value=""></th>
  </tr>
  <tr>
    <th colspan="2">
      <table cellspacing="10" >
EOQ;
showSeasonTeams();

if ($season->hasConferences) {
    showConferences();
}

echo<<< EOQ
      </table>
    </th>
  </tr>
  <tr>
  <td align="left" class="sup">This page allows you to add and remove teams from a season, and to add or remove conferences from a season.
  <br />Use the &acute;Add Conference&acute; button to add a new conference to the season. This does not save any information. 
  <br />The first pair of table allow you to remove teams from a season, or add new ones in. You cannot remove a team from a season if it has already played a game. 
  <br />If you want to add a completely new team then select the coach(es) from the left hand side who want new teams and these will be created when you hit the &acute;Update Season&acute; button. Clicking any other button will lose them.
  <br />If at least one season has been set up then all the teams currently in the season are listed with a select for each so you can change the season. The &acute;Update Conference&acute; button saves any changes. Clicking any other button will lose them.    
  <br />To change season being edited use the &acute;Change Season&acute; button at the bottom left of the page
  <br />The <a href="seasons.php">seasons</a> page allows you to to modify a season, create a new one or even delete one entirely. </td>
</tr>
  	
</form>
EOQ;

include ("includes/footer.php");
?>